// 文件路径: utils/uni-socket.js

class UniSocket {
  constructor(options = {}) {
    // 配置参数
    this.config = {
      url: options.url || 'wss://xiaolanghua.zhanyuankj.cn/wss',
      heartbeatInterval: options.heartbeatInterval || 30000, // 30秒心跳
      reconnectInterval: options.reconnectInterval || 5000,  // 5秒重连间隔
      maxReconnectAttempts: options.maxReconnectAttempts || 10, // 最大重连次数
      ...options
    }
    
    // 状态变量
    this.socketTask = null
    this.reconnectAttempts = 0
    this.heartbeatTimer = null
    this.listeners = new Map()
    this.messageQueue = []
    
    // 自动连接
    this.connect()
  }
  
  // 创建WebSocket连接
  connect() {
    // 清除旧连接
    if (this.socketTask) {
      this.socketTask.close({ reason: 'reconnecting' })
    }
    
    // 创建新连接
    uni.showLoading({ title: '连接中...', mask: true })
    this.socketTask = uni.connectSocket({
      url: this.config.url,
      header: { 'X-Client-Type': 'uni-app' },
      success: () => {
        console.log('[WebSocket] 连接创建成功')
      },
      fail: (err) => {
        console.error('[WebSocket] 连接失败', err)
        this.handleReconnect()
      }
    })
    
    // 绑定事件
    this.socketTask.onOpen(this.handleOpen.bind(this))
    this.socketTask.onMessage(this.handleMessage.bind(this))
    this.socketTask.onError(this.handleError.bind(this))
    this.socketTask.onClose(this.handleClose.bind(this))
  }
  
  // 连接打开处理
  handleOpen() {
    console.log('[WebSocket] 连接已打开')
    uni.hideLoading()
    this.reconnectAttempts = 0
    
    // 发送认证信息（根据业务需要）
    this.send({
      type: 'auth',
      payload: { 
        userId: getApp().globalData.userId,
        token: uni.getStorageSync('token')
      }
    })
    
    // 发送积压的消息
    while (this.messageQueue.length > 0) {
      const msg = this.messageQueue.shift()
      this.send(msg)
    }
    
    // 启动心跳
    this.startHeartbeat()
  }
  
  // 消息处理
  handleMessage({ data }) {
    try {
	console.log(data)
      //const msg = JSON.parse(data)
      console.log('[WebSocket] 收到消息', data)
      
      // // 处理心跳响应
      // if (msg.type === 'pong') {
      //   return
      // }
      
      // // 触发事件监听器
      // const eventListeners = this.listeners.get(msg.type) || []
      // eventListeners.forEach(callback => callback(msg.payload))
    } catch (error) {
      console.error('[WebSocket] 消息解析失败', error, data)
    }
  }
  
  // 错误处理
  handleError({ errMsg }) {
    console.error('[WebSocket] 发生错误', errMsg)
    uni.showToast({ title: '连接发生错误', icon: 'none' })
    this.handleReconnect()
  }
  
  // 连接关闭处理
  handleClose({ code, reason }) {
    console.log(`[WebSocket] 连接关闭, code=${code}, reason=${reason}`)
    
    // 非正常关闭时重新连接
    if (code !== 1000) {
      this.handleReconnect()
    }
  }
  
  // 消息发送
  send(data) {
	  console.log(888)
    // 未连接时缓存消息
    if (!this.isConnected()) {
      this.messageQueue.push(data)
      return false
    }
    
    try {
      const jsonData = typeof data === 'string' ? data : JSON.stringify(data)
      this.socketTask.send({ data: jsonData })
      return true
    } catch (error) {
      console.error('[WebSocket] 消息发送失败', error)
      this.messageQueue.push(data)
      return false
    }
  }
  
  // 注册事件监听
  on(eventType, callback) {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, [])
    }
    this.listeners.get(eventType).push(callback)
    return this
  }
  
  // 移除事件监听
  off(eventType, callback) {
    if (!callback) {
      this.listeners.delete(eventType)
    } else if (this.listeners.has(eventType)) {
      const list = this.listeners.get(eventType)
      this.listeners.set(eventType, list.filter(fn => fn !== callback))
    }
    return this
  }
  
  // 检查连接状态
  isConnected() {
    return this.socketTask && this.socketTask.readyState === 1
  }
  
  // 启动心跳
  startHeartbeat() {
    this.stopHeartbeat()
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected()) {
        this.send({ type: 'ping' })
      } else {
        this.stopHeartbeat()
      }
    }, this.config.heartbeatInterval)
  }
  
  // 停止心跳
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }
  
  // 处理重连逻辑
  handleReconnect() {
    if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
      uni.showToast({
        title: '网络连接已断开',
        icon: 'none',
        duration: 3000
      })
      return
    }
    
    this.reconnectAttempts++
    console.log(`[WebSocket] 尝试重新连接 (${this.reconnectAttempts}/${this.config.maxReconnectAttempts})`)
    
    setTimeout(() => {
      this.connect()
    }, this.config.reconnectInterval)
  }
  
  // 关闭连接
  close() {
    if (this.isConnected()) {
      this.socketTask.close({ reason: 'client_close', code: 1000 })
    }
    this.stopHeartbeat()
    this.reconnectAttempts = 0
    clearInterval(this.heartbeatTimer)
  }
  
  // 获取当前状态
  getStatus() {
    if (!this.socketTask) return 'disconnected'
    return {
      0: 'connecting',
      1: 'connected',
      2: 'closing',
      3: 'closed'
    }[this.socketTask.readyState] || 'unknown'
  }
}

// 创建单例实例
let instance = null

export const initSocket = (options) => {
  if (!instance) {
    instance = new UniSocket(options)
  }
  return instance
}

export const getSocket = () => {
  if (!instance) {
    throw new Error('WebSocket not initialized. Call initSocket first.')
  }
  return instance
}

export const closeSocket = () => {
  if (instance) {
    instance.close()
    instance = null
  }
}